<template>
  <div class="forum-posts-container">
    <!-- 搜索表单 -->
    <el-card class="search-card">
      <el-form :model="searchForm" label-width="80px" :inline="true">
        <el-form-item label="标题">
          <el-input
            v-model="searchForm.title"
            placeholder="请输入帖子标题"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="作者">
          <el-input
            v-model="searchForm.author"
            placeholder="请输入作者用户名"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable style="width: 200px">
            <el-option
              v-for="item in statusOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="排序方式">
          <el-select v-model="searchForm.orderBy" placeholder="请选择排序方式" style="width: 200px">
            <el-option
              v-for="item in orderOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="handleSearch">搜索</el-button>
          <el-button :icon="Refresh" @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作按钮 -->
    <div class="action-bar">
      <el-button type="danger" :icon="Delete" :disabled="selectedRows.length === 0" @click="handleBatchDelete">批量删除</el-button>
      <el-button type="success" :icon="Check" :disabled="selectedRows.length === 0" @click="handleBatchApprove">批量审核通过</el-button>
      <el-button type="warning" :icon="Close" :disabled="selectedRows.length === 0" @click="handleBatchReject">批量驳回</el-button>
    </div>

    <!-- 数据表格 -->
    <el-card>
      <el-table
        ref="multipleTableRef"
        v-loading="loading"
        :data="tableData"
        @selection-change="handleSelectionChange"
        style="width: 100%"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="id" label="ID" width="80" sortable />
        <el-table-column prop="title" label="标题" min-width="150" show-overflow-tooltip />
        <el-table-column prop="author" label="作者" width="120" />
        <el-table-column prop="category" label="分类" width="100" />
        <el-table-column prop="viewCount" label="浏览量" width="100" sortable align="center" />
        <el-table-column prop="likeCount" label="点赞数" width="100" sortable align="center" />
        <el-table-column prop="favCount" label="收藏数" width="100" sortable align="center" />
        <el-table-column prop="commentCount" label="评论数" width="100" align="center" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="getStatusTagType(scope.row.status)">
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="发布时间" width="180" sortable />
        <el-table-column label="操作" width="280" fixed="right">
          <template #default="scope">
            <el-button size="small" type="primary" link @click="handleDetail(scope.row)">详情</el-button>
            <el-button
              v-if="scope.row.status === 'pending'"
              size="small"
              type="success"
              link
              @click="handleApprove(scope.row)"
            >
              通过
            </el-button>
            <el-button
              v-if="scope.row.status === 'pending'"
              size="small"
              type="warning"
              link
              @click="handleReject(scope.row)"
            >
              驳回
            </el-button>
            <el-button
              size="small"
              :type="scope.row.isSticky ? 'info' : 'primary'"
              link
              @click="handleSticky(scope.row)"
            >
              {{ scope.row.isSticky ? '取消置顶' : '置顶' }}
            </el-button>
            <el-button
              size="small"
              :type="scope.row.isFeatured ? 'info' : 'primary'"
              link
              @click="handleFeatured(scope.row)"
            >
              {{ scope.row.isFeatured ? '取消精华' : '加精' }}
            </el-button>
            <el-button size="small" type="danger" link @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页组件 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 详情对话框 -->
    <el-dialog v-model="detailVisible" title="帖子详情" width="800px">
      <el-descriptions :column="2" border>
        <el-descriptions-item label="ID">{{ detail.id }}</el-descriptions-item>
        <el-descriptions-item label="作者">{{ detail.author }}</el-descriptions-item>
        <el-descriptions-item label="标题" :span="2">{{ detail.title }}</el-descriptions-item>
        <el-descriptions-item label="分类">{{ detail.category }}</el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag :type="getStatusTagType(detail.status)">
            {{ getStatusText(detail.status) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="浏览量">{{ detail.viewCount }}</el-descriptions-item>
        <el-descriptions-item label="点赞数">{{ detail.likeCount }}</el-descriptions-item>
        <el-descriptions-item label="收藏数">{{ detail.favCount }}</el-descriptions-item>
        <el-descriptions-item label="评论数">{{ detail.commentCount }}</el-descriptions-item>
        <el-descriptions-item label="置顶">
          <el-tag :type="detail.isSticky ? 'success' : 'info'">
            {{ detail.isSticky ? '是' : '否' }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="精华">
          <el-tag :type="detail.isFeatured ? 'success' : 'info'">
            {{ detail.isFeatured ? '是' : '否' }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="发布时间">{{ detail.createTime }}</el-descriptions-item>
        <el-descriptions-item label="最后更新时间">{{ detail.updateTime }}</el-descriptions-item>
      </el-descriptions>
      
      <div class="post-content">
        <h3>帖子内容</h3>
        <div v-html="detail.content"></div>
      </div>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="detailVisible = false">关闭</el-button>
          <el-button
            v-if="detail.status === 'pending'"
            type="success"
            @click="handleApprove(detail)"
          >
            通过
          </el-button>
          <el-button
            v-if="detail.status === 'pending'"
            type="warning"
            @click="handleReject(detail)"
          >
            驳回
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 驳回原因对话框 -->
    <el-dialog v-model="rejectDialogVisible" title="驳回原因" width="500px">
      <el-form :model="rejectForm" label-width="80px">
        <el-form-item label="驳回原因" prop="reason">
          <el-input
            v-model="rejectForm.reason"
            type="textarea"
            :rows="4"
            placeholder="请输入驳回原因"
          ></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="rejectDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmReject" :loading="submitLoading">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { Search, Refresh, Delete, Check, Close } from '@element-plus/icons-vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { getPostList, getPostDetail, deletePost, reviewPost, stickyPost, featuredPost } from '@/api/forum';

// 数据加载状态
const loading = ref(false);
const submitLoading = ref(false);

// 选中的行
const multipleTableRef = ref();
const selectedRows = ref([]);

// 分页参数
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);

// 表格数据
const tableData = ref([]);

// 状态选项
const statusOptions = [
  { value: 'pending', label: '待审核' },
  { value: 'approved', label: '已通过' },
  { value: 'rejected', label: '已驳回' }
];

// 排序选项
const orderOptions = [
  { value: 'createTime,desc', label: '发布时间倒序' },
  { value: 'createTime,asc', label: '发布时间正序' },
  { value: 'viewCount,desc', label: '浏览量降序' },
  { value: 'likeCount,desc', label: '点赞数降序' },
  { value: 'favCount,desc', label: '收藏数降序' }
];

// 搜索表单
const searchForm = reactive({
  title: '',
  author: '',
  status: '',
  orderBy: 'createTime,desc'
});

// 详情数据
const detailVisible = ref(false);
const detail = ref({});

// 驳回相关
const rejectDialogVisible = ref(false);
const rejectRow = ref(null);
const rejectForm = reactive({
  reason: ''
});

// 获取状态标签类型
const getStatusTagType = (status) => {
  switch (status) {
    case 'pending':
      return 'warning';
    case 'approved':
      return 'success';
    case 'rejected':
      return 'danger';
    default:
      return 'info';
  }
};

// 获取状态文本
const getStatusText = (status) => {
  switch (status) {
    case 'pending':
      return '待审核';
    case 'approved':
      return '已通过';
    case 'rejected':
      return '已驳回';
    default:
      return '未知';
  }
};

// 获取数据
const fetchData = async () => {
  loading.value = true;
  try {
    // 实际应用中应该调用API
    // const { data } = await getPostList({
    //   page: currentPage.value,
    //   pageSize: pageSize.value,
    //   title: searchForm.title,
    //   author: searchForm.author,
    //   status: searchForm.status,
    //   orderBy: searchForm.orderBy
    // });
    // tableData.value = data.list;
    // total.value = data.total;
    
    // 模拟数据
    setTimeout(() => {
      const statuses = ['pending', 'approved', 'rejected'];
      const categories = ['中药', '药膳', '养生', '健康咨询', '经验分享'];
      
      const mockData = Array.from({ length: 20 }).map((_, index) => ({
        id: index + 1,
        title: `帖子标题 ${index + 1}: 关于某某中药的使用心得`,
        author: `用户${Math.floor(Math.random() * 1000)}`,
        category: categories[index % categories.length],
        viewCount: Math.floor(Math.random() * 1000),
        likeCount: Math.floor(Math.random() * 100),
        favCount: Math.floor(Math.random() * 50),
        commentCount: Math.floor(Math.random() * 30),
        status: statuses[index % 3],
        isSticky: index < 3,
        isFeatured: index % 5 === 0,
        content: `<p>这是帖子的详细内容，包含了关于${categories[index % categories.length]}的一些心得体会和经验分享...</p>
        <p>这里有很多有用的信息，例如...</p>`,
        createTime: '2023-01-01 10:00:00',
        updateTime: '2023-01-01 10:00:00'
      }));
      
      tableData.value = mockData;
      total.value = 100;
      loading.value = false;
    }, 500);
  } catch (error) {
    console.error('获取数据失败', error);
    loading.value = false;
  }
};

// 搜索
const handleSearch = () => {
  currentPage.value = 1;
  fetchData();
};

// 重置搜索
const resetSearch = () => {
  Object.keys(searchForm).forEach(key => {
    if (key !== 'orderBy') {
      searchForm[key] = '';
    }
  });
  searchForm.orderBy = 'createTime,desc';
  currentPage.value = 1;
  fetchData();
};

// 分页处理
const handleSizeChange = (val) => {
  pageSize.value = val;
  fetchData();
};

const handleCurrentChange = (val) => {
  currentPage.value = val;
  fetchData();
};

// 表格选择行变化
const handleSelectionChange = (rows) => {
  selectedRows.value = rows;
};

// 查看详情
const handleDetail = (row) => {
  // 实际应用中应该调用API
  // const { data } = await getPostDetail(row.id);
  // detail.value = data;
  
  // 模拟数据
  detail.value = { ...row };
  detailVisible.value = true;
};

// 审核通过
const handleApprove = async (row) => {
  try {
    // 实际应用中应该调用API
    // await reviewPost(row.id, { status: 'approved' });
    
    // 模拟成功
    ElMessage({
      type: 'success',
      message: '审核通过成功'
    });
    
    // 重新加载数据
    fetchData();
    
    // 如果是在详情页操作，关闭详情页
    if (detailVisible.value) {
      detailVisible.value = false;
    }
  } catch (error) {
    console.error('操作失败', error);
    ElMessage({
      type: 'error',
      message: '操作失败'
    });
  }
};

// 驳回
const handleReject = (row) => {
  rejectRow.value = row;
  rejectForm.reason = '';
  rejectDialogVisible.value = true;
};

// 确认驳回
const confirmReject = async () => {
  if (!rejectForm.reason.trim()) {
    ElMessage({
      type: 'warning',
      message: '请输入驳回原因'
    });
    return;
  }
  
  submitLoading.value = true;
  try {
    // 实际应用中应该调用API
    // await reviewPost(rejectRow.value.id, {
    //   status: 'rejected',
    //   reason: rejectForm.reason
    // });
    
    // 模拟成功
    ElMessage({
      type: 'success',
      message: '驳回成功'
    });
    
    // 关闭对话框并刷新数据
    rejectDialogVisible.value = false;
    fetchData();
    
    // 如果是在详情页操作，关闭详情页
    if (detailVisible.value) {
      detailVisible.value = false;
    }
  } catch (error) {
    console.error('操作失败', error);
    ElMessage({
      type: 'error',
      message: '操作失败'
    });
  } finally {
    submitLoading.value = false;
  }
};

// 置顶/取消置顶
const handleSticky = async (row) => {
  try {
    // 实际应用中应该调用API
    // await stickyPost(row.id, !row.isSticky);
    
    // 模拟成功
    ElMessage({
      type: 'success',
      message: row.isSticky ? '取消置顶成功' : '置顶成功'
    });
    
    // 重新加载数据
    fetchData();
  } catch (error) {
    console.error('操作失败', error);
    ElMessage({
      type: 'error',
      message: '操作失败'
    });
  }
};

// 加精/取消加精
const handleFeatured = async (row) => {
  try {
    // 实际应用中应该调用API
    // await featuredPost(row.id, !row.isFeatured);
    
    // 模拟成功
    ElMessage({
      type: 'success',
      message: row.isFeatured ? '取消精华成功' : '加精成功'
    });
    
    // 重新加载数据
    fetchData();
  } catch (error) {
    console.error('操作失败', error);
    ElMessage({
      type: 'error',
      message: '操作失败'
    });
  }
};

// 删除
const handleDelete = (row) => {
  ElMessageBox.confirm('确定要删除该帖子吗？', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      // 实际应用中应该调用API
      // await deletePost(row.id);
      
      // 模拟删除成功
      ElMessage({
        type: 'success',
        message: '删除成功'
      });
      
      // 重新加载数据
      fetchData();
    } catch (error) {
      console.error('删除失败', error);
      ElMessage({
        type: 'error',
        message: '删除失败'
      });
    }
  }).catch(() => {});
};

// 批量删除
const handleBatchDelete = () => {
  if (selectedRows.value.length === 0) return;
  
  ElMessageBox.confirm(`确定要删除选中的 ${selectedRows.value.length} 项帖子吗？`, '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      // 实际应用中应该调用API批量删除
      // const ids = selectedRows.value.map(row => row.id);
      // await batchDeletePosts(ids);
      
      // 模拟删除成功
      ElMessage({
        type: 'success',
        message: '批量删除成功'
      });
      
      // 重新加载数据
      fetchData();
    } catch (error) {
      console.error('批量删除失败', error);
      ElMessage({
        type: 'error',
        message: '批量删除失败'
      });
    }
  }).catch(() => {});
};

// 批量审核通过
const handleBatchApprove = () => {
  if (selectedRows.value.length === 0) return;
  
  const pendingRows = selectedRows.value.filter(row => row.status === 'pending');
  if (pendingRows.length === 0) {
    ElMessage({
      type: 'warning',
      message: '没有待审核的帖子'
    });
    return;
  }
  
  ElMessageBox.confirm(`确定要批量通过选中的 ${pendingRows.length} 项待审核帖子吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'info'
  }).then(async () => {
    try {
      // 实际应用中应该调用API批量审核
      // const ids = pendingRows.map(row => row.id);
      // await batchApprovedPosts(ids);
      
      // 模拟成功
      ElMessage({
        type: 'success',
        message: '批量审核通过成功'
      });
      
      // 重新加载数据
      fetchData();
    } catch (error) {
      console.error('批量审核失败', error);
      ElMessage({
        type: 'error',
        message: '批量审核失败'
      });
    }
  }).catch(() => {});
};

// 批量驳回
const handleBatchReject = () => {
  if (selectedRows.value.length === 0) return;
  
  const pendingRows = selectedRows.value.filter(row => row.status === 'pending');
  if (pendingRows.length === 0) {
    ElMessage({
      type: 'warning',
      message: '没有待审核的帖子'
    });
    return;
  }
  
  // 这里可以弹出一个对话框，让用户输入批量驳回的原因
  rejectRow.value = { ids: pendingRows.map(row => row.id) };
  rejectForm.reason = '';
  rejectDialogVisible.value = true;
};

// 页面加载时获取数据
onMounted(() => {
  fetchData();
});
</script>

<style lang="scss" scoped>
.forum-posts-container {
  .search-card {
    margin-bottom: 20px;
  }
  
  .action-bar {
    margin-bottom: 20px;
    display: flex;
    justify-content: flex-start;
  }
  
  .pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }
  
  .post-content {
    margin-top: 20px;
    border-top: 1px solid #ebeef5;
    padding-top: 20px;
    
    h3 {
      margin-top: 0;
      margin-bottom: 15px;
      font-size: 16px;
      font-weight: 600;
    }
  }
}
</style> 